<?php
namespace Admin\Controller;

use Utuo\BackgroundController;
use Think\Model;

class ProductClassController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle("商品类目管理");
		$this->setActionTitle(array(
			'index' => '商品类目列表',
			'add' => '商品类目添加',
			'modify' => '商品类目修改',
			'recycle' => '回收站',
			'modifyAttribute' => '类目属性修改',
			'brand' => '类目品牌管理',
			'efficiency' => "产品功效管理",
		));
		$this->setActionTitle('add', '商品类目添加', array('id'=>0));
		$this->setActionNav("index,add,recycle");
	}
	
	// 商品类目列表
	public function indexAction() {
		$productClassLists = D('ProductClass')->where(array('pid'=>0, 'is_deleted'=> 0))->order("sort")->select();
		$this->assign("productClassLists", $productClassLists);
		$this->display();
	}
	
	// 商品类目添加
	public function addAction() {
		$this->display();
	}
	
	// 商品类目修改
	public function modifyAction() {
		$id = I('id', 0, "intval");
		$d = D('ProductClass');
		$productClass = $d->find($id);
		$productClass['typeOptions'] = $this->getOption($d->selectTypes, $productClass['type'], '==请设置选择模式==');
		$this->assign("productClass", $productClass);
		$this->display();
	}
	
	// 商品类目修改
	public function modifyPostAction() {
		$id = I('id', 0, "intval");
		$d = D('ProductClass');
		if($d->create()) {
			$old_pid = M('ProductClass')->where("id={$id}")->getField('pid');
			if(isset($d->pid) and $d->pid !== $old_pid){
				$m = M('ProductClass');
				/*新的父结点*/
				$nowParent = $m->find($d->pid);
				$nowParent or $level = 0;
				$nowParent and $level = $nowParent['level'] + 1;
				/*所有子结点id*/
				$count = array($level => 1); //每级节点数量
				$ids = $nowData = array($d->id);
				while($m->where(array("pid" => array("in", $nowData)))->count()) {
					$conditon = array("pid" => array("in", $nowData));
					$nowData = $m->where($conditon)->getField("id", true);
					$ids = array_merge($ids, $nowData);
					$count[++$level] = count($nowData);
				}
				/*验证父结点*/
				if(in_array($d->pid, $ids)){
					$this->ajaxError("新指定的父栏不能为当前栏目或其子级");
				}
				/*更新级别*/
				$offset = 0;
				foreach($count as $l => $c) { 
					$uIds = array_slice($ids, $offset, $c);
					$m->where(array('id' => array('in', $uIds)))->setField("level", $l);
					$offset+=$c;
				}
				/*更新是否有孩子*/
				$this->checkHasChild($old_pid);
				$m->where("id=%d", $this->pid)->setField("has_child", 1);
			}
			if(false !== $d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError($d->getError());
	}
	
	// 类目添加
	public function addPostAction() {
		$id = I('id', 0, "intval");
		$d = D('ProductClass');
		if($d->create()) {
			/*计算级别*/
			$level = -1;
			if($d->pid){
				$parent = M('ProductClass')->find($d->pid);
				$level = $parent['level'];
			}
			$d->level = $level + 1;
			/*添加*/
			if(false !== $d->add()) {
				$d->pid or M('ProductClass')->where("id=%d", $d->pid)->setField("has_child", 1);
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError($d->getError());
	}
	
	// 获取子类目
	public function ajaxPostAction() {
		$id = I('id', 0, 'intval');
		$d = D('ProductClass');
		$data = $d->where(array('pid'=>$id, 'is_deleted'=> 0))->order('sort')->select();
		$this->ajaxSuccess('', $data);
	}
	
	// 移除类目
	public function removePostAction() {
		$id = I('id', 0, "intval");
		$d = D('ProductClass');
		if($d->where("pid={$id} and is_deleted=0")->count()){
			$this->ajaxError('存在子类目不能移除.');
		}
		$this->addEventListener("afterRemove", function($e, $scope) { call_user_method("checkHasChild", $scope);  });
		$this->ajaxRemove();
	}

	
	// 删除类目
	public function deletePostAction() {
		$id = I('id', 0, "intval");
		$d = D('ProductClass');
		if($d->where("pid={$id} and is_deleted=1")->count()){
			$this->ajaxError('存在子类目不能删除.');
		}
		$this->ajaxDelete();
	}
	
	// 恢复类目
	public function restorePostAction() {
		$m = M("ProductClass");
		$productClass = $this->getOneById("ProductClass");
		// 有父栏先恢复父栏
		if($productClass['pid']) {
			$parentCategory = $m->find($productClass['pid']);
			if($parentCategory['is_deleted']) $this->ajaxError("存在父类目必须先恢复父类目.");
		}
		$this->addEventListener("afterRestore", function($e, $scope) { call_user_method("checkHasChild", $scope);  });
		$this->ajaxRestore("ProductClass");
	}
	
	// 回收站
	public function recycleAction() {
		$d = D('ProductClass');
		$condition = array('is_deleted'=> 1);
		$productClassLists = $d->where($condition)->limit($this->getPageSize())->page($this->getPage())->order('sort')->select();
		$productClassCount = $d->where($condition)->count();
		$this->showPage($productClassCount, $this->getPageSize());
		$this->assign("productClassLists", $productClassLists);
		$this->display();
	}
	
	// 修改类目的属性
	public function modifyAttributeAction() {
		$classId = I('id', 0, "intval"); // 类目ID
		$productClass = $this->getOneById("ProductClass");
		$productAttributeLists = M("ProductAttribute")->where(array(
															'id' => array('in', $productClass['attributes'])) 
														)->order("id asc")->select();
		foreach ($productAttributeLists as &$v) {
			$v['values'] = trim(preg_replace('/(\,)\d+\|/', '$1', $v['values']), ",");
		}
		$productClass['attributes'] = $productAttributeLists;
		$this->assign("productClass", $productClass);
		$this->display();
	}
	
	// 属性批量修改提交
	public function modifyAttributePostAction() {
		$d = M("ProductAttribute");
		$dProductClass = M("ProductClass");
		$data = I("data", array());
		$classId = I("class_id", 0);
		$ids = array(); // 属性id集合
		foreach($data as $v) {
			// 格式验证
			$values = "";
			foreach (explode(',', $v['values']) as $value) {
				if($value) $values .= ','.sprintf("%u",crc32("$value")).'|'.$value;
			}
			empty($values) or $values = "$values,";
			// 添加与更新
			$item = array(
					'name'=> $v['name'],
					'values'=> $values,
					'multiselect' => $v['multiselect']?1:0,
					'is_standard' => $v['is_standard']?1:0
			);
			empty($v['class_id'])?$item['class_id']=$classId:$item['class_id'] = $v['class_id'];
			if(!empty($v['id'])) {
				$ids[] = $item['id'] = $v['id'];
				$d->save($item);
			} else $id = $d->add($item) and $ids[] = $id;
		}
		( false!==$dProductClass->where("id=$classId")->save(array("attributes" => join(',',$ids))) and
		  false!==$d->where(array('id' => array('not in', $ids), 'class_id' => $classId))->delete() ) or $this->ajaxError("保存失败");
		$this->ajaxSuccess();
	}
	
	// 继承父类目属性列表
	public function extendAttributesPostAction() {
		$method = I("method", 0, "intval");
		$classId = I("class_id", 0);
		$d = M("ProductClass");
		$productAttributeLists = array();
		$productClass = $d->find($classId);
		if( $productClass['pid'] != 0 ) {
			$fields = array("name", "values");
			!$method or array_merge($fields, array("id", "class_id"));
			$productClass = $d->find($productClass['pid']);
			$productAttributeLists = M("ProductAttribute")->where(array(
					'id' => array('in', $productClass['attributes']))
			)->field()->order("id asc")->select();
			foreach ($productAttributeLists as &$v) {
				$v['values'] = trim(preg_replace('/(\,)\d+\|/', '$1', $v['values']), ",");
			}
		}
		$this->ajaxSuccess('', $productAttributeLists);
	}
	
	// 删除属性
	public function deleteAttributePostAction() {
		$classId = I("class_id", 0);
		$attrId = I("attr_id", 0);
		$m = M("ProductAttribute");
		$productClass = M("ProductClass")->find($classId);
		$attr = trim(preg_replace("/\,?$attrId\,?/", ',', trim($productClass['attributes'], ",")), ",");
		(false === $m->where(array('id' => $attrId, 'class_id' => $classId))->delete() or 
		 false === $productClass->where("id=$classId")->setField("attributes", $attr)) and $this->ajaxError("删除失败");
		$this->ajaxError("删除成功");
	}
	
	
	// 检查栏目父类是否有孩子
	public function checkHasChild($pid) {
		$id = I('id', 0, "intval");
		$pid or $pid = M('ProductClass')->where("id=%d", $id)->getField("pid");
		if($pid){
			$has_child = M('ProductClass')->where("pid=%d and is_deleted=0", $pid)->count()?1:0;
			M('ProductClass')->where("id=%d", $pid)->setField("has_child", $has_child);
		}
	}
	
	// 类目品牌
	public function brandAction() {
		$id = I('id', 0, 'intval');
		do {
			$productClass = M("ProductClass")->where("id=%d", $id)->find();
			if ( !$productClass or !empty($productClass['brand']) ) {
				break;
			}
			$id = $productClass['pid'];
		} while( $id != 0 );
		$productBrandLists = M("ProductBrand")->where(array('id'=>array('in', trim($productClass['brand'], ", "))))->order("field(id,".trim($productClass['brand'], ", ").")")->field("id,name")->select();
		$this->assign("productBrandLists", $productBrandLists);
		$this->assign("productBrandJSON", json_encode($productBrandLists));
		$this->assign("id", $id);
		$this->display();
	}
	
	// 保存品牌
	public function saveBrandAction() {
		if( M("ProductClass")->field('id,brand')->create() ) {
			false !== M("ProductClass")->save() and $this->ajaxSuccess("保存成功");
		}
		$this->ajaxSuccess("保存失败");
	}
	
	// 类目功效
	public function efficiencyAction() {
		$id = I('id', 0, 'intval');
		do {
			$productClass = M("ProductClass")->where("id=%d", $id)->find();
			if ( !$productClass or !empty($productClass['efficiency']) ) {
				break;
			}
			$id = $productClass['pid'];
		} while( $id != 0 );
		$productEfficiencyLists = M("ProductEfficiency")->where(array('id'=>array('in', trim($productClass['efficiency'], ", "))))->order("field(id,".trim($productClass['efficiency'], ", ").")")->field("id,name")->select();
		$this->assign("productEfficiencyLists", $productEfficiencyLists);
		$this->assign("productEfficiencyJSON", json_encode($productEfficiencyLists));
		$this->assign("id", $id);
		$this->display();
	}
	
	// 保存功效
	public function saveEfficiencyAction() {
		if( M("ProductClass")->field('id,efficiency')->create() ) {
			false !== M("ProductClass")->save() and $this->ajaxSuccess("保存成功");
		}
		$this->ajaxSuccess("保存失败");
	}
}